package com.example.mangroves.controller;

import com.example.mangroves.entity.Phenology;
import com.example.mangroves.entity.RGBData;
import com.example.mangroves.entity.InfraredData;
import com.example.mangroves.mapper.InfraredDataMapper;
import com.example.mangroves.mapper.PhenologyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@RestController
public class DataUploadController {

    @PostMapping("/upload-data")
    public ResponseEntity<String> uploadData(@RequestBody String csvData) {
        // 预处理输入数据，删除末尾的空白字符和换行
        csvData = csvData.trim().replace("/r", "").replace("/n", "");

        // 解析CSV数据
        String[] lines = csvData.split("\r\n");
        List<RGBData> rgbDataList = new ArrayList<>();
        List<InfraredData> infraredDataList = new ArrayList<>();

        //解析每行传入的涡度数据，以字段个数作为RGB和红外图像数据的划分
        for (String line : lines) {
            // 忽略空行
            if (line.isEmpty()) {
                continue;
            }

            String[] values = line.split(",");
            try {
                switch (values.length) {
                    case 9:  // RGB data processing
                        RGBData rgbData = parseRGBData(values);
                        rgbDataList.add(rgbData);
                        break;
                    case 5:  // Infrared data processing
                        InfraredData infraredData = parseInfraredData(values);
                        infraredDataList.add(infraredData);
                        break;
                    default:
                        // Log error or handle unexpected data format
                        return ResponseEntity.badRequest().body("Invalid data format received");
                }
            } catch (NumberFormatException e) {
                return ResponseEntity.badRequest().body("Error in data conversion: " + e.getMessage());
            }
        }

        // Process or store the parsed data
        processRGBData(rgbDataList);
        processInfraredData(infraredDataList);

        // Assuming the processing is successful
        return ResponseEntity.ok("OK");
    }

    private RGBData parseRGBData(String[] values) {
        RGBData data = new RGBData();
        data.setImgDatetime(values[0]);
        data.setGcc(Double.parseDouble(values[1]));
        data.setGvi(Double.parseDouble(values[2]));
        data.setName(values[3]);
        data.setCameraID(Integer.parseInt(values[4]));
        data.setExposureTime(Integer.parseInt(values[5]));
        data.setRcc(Double.parseDouble(values[6]));
        data.setBcc(Double.parseDouble(values[7]));
        data.setFileSize(Integer.parseInt(values[8]));
        return data;
    }

    private InfraredData parseInfraredData(String[] values) {
        InfraredData data = new InfraredData();
        data.setImgDatetime(values[0]);
        data.setMeanNDVI(Double.parseDouble(values[1]));
        data.setRoiNDVI(Double.parseDouble(values[2]));
        data.setName(values[3]);
        data.setCameraID(Integer.parseInt(values[4]));
        return data;
    }

    @Autowired
    private InfraredDataMapper infrareddataMapper;
    @Autowired
    private PhenologyMapper phenologyMapper;

    public void processInfraredData(List<InfraredData> dataList) {
        for (InfraredData data : dataList) {
            infrareddataMapper.insert(data);
            // 可以选择在这里记录每次插入的ID，或者不做处理
        }
    }

    public void processRGBData(List<RGBData> dataList) {
        Long lastInfraredId = infrareddataMapper.selectLastId();  // 获取最后一个红外数据ID
        InfraredData lastInfraredData = infrareddataMapper.selectById(lastInfraredId);

        for (RGBData rgbData : dataList) {
            Phenology phenology = new Phenology();
            // 填充物候数据
            phenology.setNdvi(lastInfraredData.getMeanNDVI());
            phenology.setRoiNdvi(lastInfraredData.getRoiNDVI());
            // 填充RGB数据
            phenology.setGcc(rgbData.getGcc());
            phenology.setGvi(rgbData.getGvi());
            phenology.setRcc(rgbData.getRcc());
            phenology.setBcc(rgbData.getBcc());
            // 设置当前时间
            phenology.setTime(new Timestamp(System.currentTimeMillis()));
            // 设置low_lai为100到300之间的随机值
            phenology.setLowlai(100 + Math.random() * 200);
            // 设置fvc为0.01到0.5之间的随机值
            phenology.setFvc(0.01 + Math.random() * 0.49);

            phenologyMapper.insertPhenology(phenology);
        }
    }
}
